package com.hgyc.mom.common.util;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

/**
 * 加密解密工具类
 * @author fwj
 * @since 2025-08-08
 */
public class CryptoUtils {
    static byte[] bytesKey = {64, -108, 7, -9, -20, -113, 104, -119};

    public static String encode(String data) {
        try {
            DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            Key convertSecretKey = factory.generateSecret(desKeySpec);
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
            byte[] bytes = data.getBytes();
            int len = Math.max(30, bytes.length + 4);
            byte[] source = new byte[len];
            int idx = 0;
            for (byte b : ObjectUtils.toByteArray(bytes.length)) {
                source[idx++] = b;
            }
            for (byte b : bytes) {
                source[idx++] = b;
            }
            while (idx < len) {
                source[idx++] = (byte) idx;
            }
            byte[] result = cipher.doFinal(source);
            return Hex.encodeHexString(result);
        } catch (Exception e) {
            return "error";
        }
    }

}
